package com.taotao.proxy.service.mybatis;

import com.taotao.proxy.service.mybatis.ext.MayiktInsert;
import com.taotao.proxy.service.utils.MayiktJdbcUtils;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.PreparedStatement;

/**
 * @Author: wangjin
 * @CreateTime: 2022-07-05  22:58
 */
public class MybatisInvocationHandler  implements InvocationHandler {
    private  Class mapperClass;
    public MybatisInvocationHandler(Class mapperClass){
        this.mapperClass=mapperClass;
    }
    /**
     *
     * @param proxy
     * @param method
     * @param args
     * @return
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
       //当我们在调用userMapper.addUser()
         //使用java 反射机制获取方法上 注解
        MayiktInsert mayiktInsert=method.getDeclaredAnnotation(MayiktInsert.class);
        //获取注解中的sql 执行
        String insertSQL =mayiktInsert.value();
        Connection connection= MayiktJdbcUtils.getConnection();
        PreparedStatement preparedStatement=connection.prepareStatement(insertSQL);

        // 执行完毕后将返回结果
        return preparedStatement.executeUpdate();
    }

    public <T> T getProxy(){

        return  (T) Proxy.newProxyInstance(mapperClass.getClassLoader(),new Class[]{mapperClass},this);
    }
}
